#在3sigma之外可看作前景
import cv2 as cv
videoFileName = r'E:\images\vtest.avi'
cap = cv.VideoCapture(videoFileName)
fgbg  = cv.createBackgroundSubtractorMOG2()
thresh = 200
while True:
    ret, frame = cap.read()
    if not ret:
        break

    fgmask = fgbg.apply(frame)
    _, fgmask = cv.threshold(fgmask, 30, 0xff, cv.THRESH_BINARY)
    fgmask = cv.morphologyEx(fgmask, cv.MORPH_OPEN, se)
    bgImage = fgbg.getBackgroundImage()

    cnts, _ = cv.findContours(fgmask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)#前景分割
    count =0
    for c in cnts:
        area = cv.contourArea(c)
        if(area < thresh):
            continue
        count += 1

        x, y, w, h = cv.boundingRect(c)
        cv.rectangle(frame, (x, y), (x+w, y+h), (0, 0xff, 0), 2)
        print(" 面积: ", area, "位置x：", x, "位置y:", y)

    print('共检测到', count, '个目标', '\n')
    cv.imshow('frame', frame)
    cv.imshow('Backgroud', bgImage)
    cv.imshow('Frontgroud', fgmask) #前景


    key = cv.waitKey(30)
    if key == 27:
        break
    cap.release()
    cv.destroyAllWindows()